import 'package:flutter/material.dart';
import 'package:get/get.dart';
import '../controllers/product_model_detail_controller.dart';
import '../../../utils/themes/app_theme.dart';
import '../../../utils/themes/app_theme_extension.dart';
import '../../../models/thing_model.dart';
import '../../../utils/json_utils.dart';
import '../../../translations/app_translations.dart';

class ProductModelDetailView extends GetView<ProductModelDetailController> {
  const ProductModelDetailView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();

    return Scaffold(
      appBar: AppBar(
        title: Text(LocaleKeys.productInfo.tr),
        centerTitle: true,
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: controller.refreshData,
          ),
        ],
      ),
      body: Obx(() {
        if (controller.isLoading.value) {
          return const Center(child: CircularProgressIndicator());
        }

        if (controller.hasError.value) {
          return Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  controller.errorMessage.value,
                  style: TextStyle(color: extension?.errorText),
                ),
                const SizedBox(height: 16),
                ElevatedButton(
                  onPressed: controller.refreshData,
                  child: Text(LocaleKeys.retry.tr),
                ),
              ],
            ),
          );
        }

        // 输出调试信息
        debugPrint('物模型列表数量: ${controller.thingModels.length}');

        return RefreshIndicator(
          onRefresh: controller.refreshData,
          child: ListView(
            padding: const EdgeInsets.all(16),
            children: [
              // 物模型JSON
              _buildCard(
                context,
                title: LocaleKeys.totalModels.tr,
                actions: [
                  const IconButton(
                    icon: Icon(Icons.edit),
                    tooltip: 'Edit Model (Disabled)',
                    onPressed: null,
                    color: Colors.grey,
                  ),
                ],
                child: _buildThingModelsList(context),
              ),
            ],
          ),
        );
      }),
    );
  }

  // 构建物模型列表
  Widget _buildThingModelsList(BuildContext context) {
    final extension = Theme.of(context).extension<AppThemeExtension>();
    final thingModels = controller.thingModels;

    // 调试输出
    debugPrint('构建物模型列表，数量: ${thingModels.length}');

    if (thingModels.isEmpty) {
      return Padding(
        padding: const EdgeInsets.symmetric(vertical: 32),
        child: Center(
          child: Column(
            children: [
              Icon(
                Icons.info_outline,
                size: 48,
                color: extension?.textSecondary.withOpacity(0.5),
              ),
              const SizedBox(height: 16),
              Text(
                LocaleKeys.noDevices.tr,
                style: TextStyle(
                  color: extension?.textSecondary,
                  fontSize: 16,
                ),
              ),
            ],
          ),
        ),
      );
    }

    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: thingModels.length,
      itemBuilder: (context, index) {
        final model = thingModels[index];

        // 调试输出
        debugPrint('构建物模型卡片: ${model.modelId}');

        return _buildThingModelCard(context, model);
      },
    );
  }

  Widget _buildCard(BuildContext context,
      {required String title, required Widget child, List<Widget>? actions}) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();

    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(extension?.cardRadius ?? 8),
        side: BorderSide(color: extension?.cardBorder ?? Colors.grey.shade200),
      ),
      elevation: 2,
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Padding(
              padding: const EdgeInsets.only(bottom: 12),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      title,
                      style: theme.textTheme.titleMedium?.copyWith(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                  if (actions != null)
                    Row(
                      mainAxisSize: MainAxisSize.min,
                      children: actions,
                    ),
                ],
              ),
            ),
            child,
          ],
        ),
      ),
    );
  }

  Widget _buildThingModelCard(BuildContext context, ThingModel model) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();

    // 解析JSON数据 - 使用ThingModel的辅助方法
    Map<String, dynamic> modelJson = model.getParsedModelJson();

    // 计算各部分项目数量
    int propertiesCount = modelJson.containsKey('properties')
        ? (modelJson['properties'] as List).length
        : 0;
    int servicesCount = modelJson.containsKey('services')
        ? (modelJson['services'] as List).length
        : 0;
    int eventsCount = modelJson.containsKey('events')
        ? (modelJson['events'] as List).length
        : 0;

    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(extension?.cardRadius ?? 8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 物模型头部信息
          Padding(
            padding: const EdgeInsets.all(16),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Expanded(
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '${LocaleKeys.totalModels.tr} v${model.modelVersion ?? "1.0.0"}',
                            style: const TextStyle(
                                fontWeight: FontWeight.bold, fontSize: 16),
                          ),
                          const SizedBox(height: 4),
                          Text(
                            '${LocaleKeys.status.tr}: ${model.modelStatus == 1 ? LocaleKeys.statusSuccess.tr : LocaleKeys.statusInfo.tr}',
                            style: TextStyle(
                                fontSize: 13, color: extension?.textSecondary),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
                // 显示统计信息
                const SizedBox(height: 8),
                Wrap(
                  spacing: 8,
                  runSpacing: 4,
                  children: [
                    _buildStatChip(
                        context, 'Properties: $propertiesCount', Colors.blue),
                    _buildStatChip(
                        context, 'Services: $servicesCount', Colors.green),
                    _buildStatChip(
                        context, 'Events: $eventsCount', Colors.orange),
                  ],
                ),
              ],
            ),
          ),

          // 调试按钮
          Padding(
            padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.end,
              children: [
                InkWell(
                  onTap: () => _showRawJsonDialog(context, model),
                  child: Text(
                    'View Raw Data',
                    style: TextStyle(
                      fontSize: 12,
                      color: theme.colorScheme.primary,
                      decoration: TextDecoration.underline,
                    ),
                  ),
                ),
              ],
            ),
          ),

          // 展开和折叠控制按钮
          ExpansionTile(
            title: Text(LocaleKeys.viewDetails.tr),
            initiallyExpanded: true,
            children: [
              // 属性列表
              if (propertiesCount > 0)
                _buildModelSection(
                    context, 'Properties', modelJson['properties'] as List),

              // 服务列表
              if (servicesCount > 0)
                _buildModelSection(
                    context, 'Services', modelJson['services'] as List),

              // 事件列表
              if (eventsCount > 0)
                _buildModelSection(
                    context, 'Events', modelJson['events'] as List),

              // 如果没有解析出结构化数据，显示原始JSON
              if (modelJson.isEmpty && model.modelJson != null)
                Padding(
                  padding: const EdgeInsets.all(16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Model JSON Data:',
                        style: TextStyle(
                          fontWeight: FontWeight.bold,
                          color: extension?.textSecondary,
                        ),
                      ),
                      const SizedBox(height: 8),
                      Container(
                        width: double.infinity,
                        padding: const EdgeInsets.all(12),
                        decoration: BoxDecoration(
                          color:
                              theme.colorScheme.surfaceContainerHighest.withOpacity(0.5),
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Text(
                          model.modelJson.toString(),
                          style: TextStyle(
                            fontFamily: 'monospace',
                            fontSize: 12,
                            color: extension?.textSecondary,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
            ],
          ),
        ],
      ),
    );
  }

  // 添加统计数字标签
  Widget _buildStatChip(BuildContext context, String label, Color color) {
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.3), width: 1),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.bold,
          color: color,
        ),
      ),
    );
  }

  Widget _buildModelSection(BuildContext context, String title, List items) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();

    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 8),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Padding(
            padding: const EdgeInsets.symmetric(vertical: 8),
            child: Text(
              title,
              style: theme.textTheme.titleSmall?.copyWith(
                fontWeight: FontWeight.bold,
                color: theme.colorScheme.primary,
              ),
            ),
          ),
          ListView.builder(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            itemCount: items.length,
            itemBuilder: (context, index) {
              final item = items[index];
              return _buildModelItem(context, item);
            },
          ),
        ],
      ),
    );
  }

  Widget _buildModelItem(BuildContext context, dynamic item) {
    final theme = Theme.of(context);
    final extension = theme.extension<AppThemeExtension>();

    String name = item['name'] ?? LocaleKeys.unknown.tr;
    String identifier = item['identifier'] ?? '';
    String dataType = item['dataType'] ?? LocaleKeys.unknown.tr;
    // 优先使用desc字段，如果不存在则使用description
    String description = item['desc'] ?? item['description'] ?? '';

    return Card(
      margin: const EdgeInsets.only(bottom: 8),
      color: extension?.cardBackground,
      child: Padding(
        padding: const EdgeInsets.all(12),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    name,
                    style: theme.textTheme.titleSmall?.copyWith(
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                Container(
                  padding:
                      const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
                  decoration: BoxDecoration(
                    color:
                        _getDataTypeColor(dataType, context).withOpacity(0.1),
                    borderRadius: BorderRadius.circular(4),
                  ),
                  child: Text(
                    dataType,
                    style: TextStyle(
                      fontSize: 12,
                      color: _getDataTypeColor(dataType, context),
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 4),
            Text(
              'Identifier: $identifier',
              style: TextStyle(
                color: extension?.textSecondary,
                fontSize: 12,
              ),
            ),
            if (description.isNotEmpty) const SizedBox(height: 4),
            if (description.isNotEmpty)
              Text(
                description,
                style: TextStyle(
                  color: extension?.textSecondary,
                  fontSize: 13,
                ),
              ),

            // 显示额外属性（最小值、最大值、单位等）
            if (_hasRangeProperties(item))
              Padding(
                padding: const EdgeInsets.only(top: 8),
                child: Wrap(
                  spacing: 8,
                  runSpacing: 4,
                  children: [
                    if (item['min'] != null)
                      _buildPropertyChip(context, 'Min: ${item['min']}'),
                    if (item['max'] != null)
                      _buildPropertyChip(context, 'Max: ${item['max']}'),
                    if (item['unit'] != null)
                      _buildPropertyChip(context, 'Unit: ${item['unit']}'),
                  ],
                ),
              ),
          ],
        ),
      ),
    );
  }

  Widget _buildPropertyChip(BuildContext context, String label) {
    final theme = Theme.of(context);
    final extension = Theme.of(context).extension<AppThemeExtension>();

    return Container(
      margin: const EdgeInsets.only(right: 8),
      padding: const EdgeInsets.symmetric(horizontal: 6, vertical: 2),
      decoration: BoxDecoration(
        color: theme.colorScheme.surface,
        borderRadius: BorderRadius.circular(4),
      ),
      child: Text(
        label,
        style: TextStyle(
          fontSize: 11,
          color: extension?.textSecondary,
        ),
      ),
    );
  }

  bool _hasRangeProperties(dynamic item) {
    return item['min'] != null || item['max'] != null || item['unit'] != null;
  }

  Color _getDataTypeColor(String dataType, BuildContext context) {
    final extension = AppTheme.extensionOf(context);

    switch (dataType.toLowerCase()) {
      case 'int':
      case 'float':
      case 'double':
        return Colors.blue;
      case 'bool':
        return Colors.green;
      case 'string':
        return Colors.orange;
      case 'enum':
        return Colors.purple;
      case 'struct':
      case 'array':
        return Colors.teal;
      default:
        return extension.textSecondary ?? Colors.grey;
    }
  }

  // 显示原始JSON数据对话框
  void _showRawJsonDialog(BuildContext context, ThingModel model) {
    final theme = Theme.of(context);

    // 获取JSON类型信息
    String jsonTypeInfo = 'Type: ${model.modelJson.runtimeType}';

    // 尝试检测JSON结构
    String structureInfo = '';
    if (model.modelJson is Map) {
      structureInfo =
          'Structure: Map with ${(model.modelJson as Map).length} keys';
      if ((model.modelJson as Map).isNotEmpty) {
        structureInfo += '\nKeys: ${(model.modelJson as Map).keys.join(', ')}';
      }
    } else if (model.modelJson is String) {
      structureInfo =
          'Structure: String of length ${(model.modelJson as String).length}';
      // 显示前20个字符用于预览
      if ((model.modelJson as String).isNotEmpty) {
        final preview = (model.modelJson as String).length > 20
            ? '${(model.modelJson as String).substring(0, 20)}...'
            : model.modelJson;
        structureInfo += '\nPreview: $preview';
      }
    }

    Get.dialog(
      Dialog(
        child: Container(
          width: Get.width * 0.9,
          height: Get.height * 0.7,
          padding: const EdgeInsets.all(16),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Expanded(
                    child: Text(
                      'Thing Model Raw Data',
                      style: theme.textTheme.titleLarge,
                      overflow: TextOverflow.ellipsis,
                    ),
                  ),
                  IconButton(
                    icon: const Icon(Icons.close),
                    onPressed: () => Get.back(),
                  ),
                ],
              ),
              const SizedBox(height: 8),
              Text(
                jsonTypeInfo,
                style: theme.textTheme.bodySmall,
              ),
              Text(
                structureInfo,
                style: theme.textTheme.bodySmall,
              ),
              const SizedBox(height: 16),
              Expanded(
                child: Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: theme.colorScheme.surfaceContainerHighest.withOpacity(0.3),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 如果是Map类型，尝试格式化显示
                        if (model.modelJson is Map)
                          Text(
                            JsonUtils.formatJsonString(model.modelJson),
                            style: const TextStyle(
                              fontFamily: 'monospace',
                              fontSize: 12,
                            ),
                          )
                        // 如果是String类型，尝试格式化
                        else if (model.modelJson is String)
                          Text(
                            model.modelJson.toString(),
                            style: const TextStyle(
                              fontFamily: 'monospace',
                              fontSize: 12,
                            ),
                          )
                        // 其他类型直接显示
                        else
                          Text(
                            model.modelJson.toString(),
                            style: const TextStyle(
                              fontFamily: 'monospace',
                              fontSize: 12,
                            ),
                          ),
                      ],
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
